package com.hko.qrip.manager;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;

import java.io.File;

public class FTPManager {

	FTPClient ftpClient = null;

	private String url;
	private String username;
	private String password;

	public FTPManager(String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
	}

	public boolean ftpLogin() {
		ftpClient = new FTPClient();
		try {

			ftpClient.connect(url);
			ftpClient.setType(FTPClient.TYPE_AUTO);
			ftpClient.setCharset("UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			ftpClient.login(username, password);
		} catch (Exception e) {
			e.printStackTrace();

		}
		return true;
	}

	public void changeDir(String path) {
		if (null != ftpClient) {
			try {
				ftpClient.changeDirectory(path);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void close() {
		if (null != ftpClient) {
			try {
				ftpClient.disconnect(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void downloadAndDeleteFile(String localFilePath, String remoteFileName) throws Exception {
		File localFile = new File(localFilePath);
		try {
			ftpClient.download(remoteFileName, localFile);
			ftpClient.deleteFile(remoteFileName);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public void downloadFile(File localFile, String remoteFileName) throws Exception {
		try {
			ftpClient.download(remoteFileName, localFile);
		} catch (Exception e) {
			e.printStackTrace();

			throw e;
		}
	}

	public FTPFile[] listFiles(String pattern) {
		FTPFile[] fileNames = null;
		try {
			fileNames = this.ftpClient.list(pattern);
		} catch (Exception e) {
			e.printStackTrace();

		}
		return fileNames;
	}

	public String[] listNames() {
		String fileNames[] = null;
		try {
			fileNames = this.ftpClient.listNames();
		} catch (Exception e) {
			e.printStackTrace();

		}
		return fileNames;
	}

	public String getURL() {
		return url;
	}

	public void setURL(String uRL) {
		url = uRL;
	}

	public String getUSERNAME() {
		return username;
	}

	public void setUSERNAME(String uSERNAME) {
		username = uSERNAME;
	}

	public String getPASSWORD() {
		return password;
	}

	public void setPASSWORD(String pASSWORD) {
		password = pASSWORD;
	}

}